import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Row, Col, Statistic, Table, Form, Select, DatePicker, Button, Space, Tabs, message } from 'antd';
import { request } from 'umi';
import { Line, Pie, Column } from '@ant-design/charts';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 获取团购统计数据
const fetchStatistics = async (params) => {
  return request('/api/v1/groupbuy/statistics', {
    method: 'GET',
    params,
  });
};

const GroupbuyStatistics = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [statistics, setStatistics] = useState({});
  const [activities, setActivities] = useState([]);
  const [activeTab, setActiveTab] = useState('overview');
  const [timeRange, setTimeRange] = useState('week'); // week, month, year

  // 获取团购活动列表
  const fetchActivities = async () => {
    try {
      const res = await request('/api/v1/groupbuy/activity', {
        method: 'GET',
        params: { pageSize: 100 },
      });
      if (res.success) {
        // 确保设置的是数组数据
        setActivities(res.data?.list || []);
      }
    } catch (error) {
      console.error('获取活动列表出错:', error);
      message.error('获取活动列表失败');
      // 出错时设置空数组
      setActivities([]);
    }
  };

  // 获取统计数据
  const fetchStatisticsData = async (params = {}) => {
    try {
      setLoading(true);
      const res = await fetchStatistics({
        timeRange,
        ...params,
      });
      if (res.success) {
        setStatistics(res.data || {});
      }
    } catch (error) {
      console.error('获取统计数据出错:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchActivities();
    fetchStatisticsData();
  }, [timeRange]);

  // 处理搜索
  const handleSearch = (values) => {
    const params = {
      timeRange,
      ...values,
    };
    if (values.date_range && values.date_range.length === 2) {
      params.startTime = values.date_range[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.date_range[1].format('YYYY-MM-DD HH:mm:ss');
    }
    fetchStatisticsData(params);
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchStatisticsData();
  };

  // 销售额趋势图配置
  const salesConfig = {
    data: statistics.sales_trend || [],
    xField: 'date',
    yField: 'amount',
    seriesField: 'type',
    yAxis: {
      label: {
        formatter: (v) => `¥${(v / 100).toFixed(2)}`,
      },
    },
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
  };

  // 订单数量趋势图配置
  const orderConfig = {
    data: statistics.orderTrend || [],
    xField: 'date',
    yField: 'count',
    seriesField: 'type',
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
  };

  // 活动分布饼图配置
  const activityPieConfig = {
    data: statistics.activityDistribution || [],
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'pie-legend-active' }, { type: 'element-active' }],
  };

  // 热门活动柱状图配置
  const popularConfig = {
    data: statistics.popularActivities || [],
    xField: 'name',
    yField: 'count',
    label: {
      position: 'middle',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
    },
    meta: {
      name: { alias: '活动名称' },
      count: { alias: '订单数量' },
    },
  };

  // 活动分析表格列定义
  const activityColumns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '订单数',
      dataIndex: 'order_count',
      key: 'order_count',
    },
    {
      title: '销售额',
      dataIndex: 'sales_amount',
      key: 'sales_amount',
      render: (amount) => `¥${(amount / 100).toFixed(2)}`,
    },
    {
      title: '成团率',
      dataIndex: 'success_rate',
      key: 'success_rate',
      render: (rate) => `${(rate * 100).toFixed(2)}%`,
    },
  ];

  return (
    <PageContainer>
      <Card style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="activityId" label="活动名称">
            <Select placeholder="请选择活动" style={{ width: 200 }} allowClear>
              {Array.isArray(activities) && activities.map(activity => (
                <Option key={activity.id} value={activity.id}>{activity.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="时间范围">
            <RangePicker
              format="YYYY-MM-DD"
              placeholder={['开始日期', '结束日期']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <div style={{ marginBottom: 16 }}>
          <Space size="large">
            <Button 
              type={timeRange === 'week' ? 'primary' : 'default'} 
              onClick={() => setTimeRange('week')}
            >
              最近一周
            </Button>
            <Button 
              type={timeRange === 'month' ? 'primary' : 'default'} 
              onClick={() => setTimeRange('month')}
            >
              最近一月
            </Button>
            <Button 
              type={timeRange === 'year' ? 'primary' : 'default'} 
              onClick={() => setTimeRange('year')}
            >
              最近一年
            </Button>
          </Space>
        </div>
      </Card>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="概览" key="overview">
          <Row gutter={24}>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="总销售额" 
                  value={statistics.totalSales ? (statistics.totalSales / 100).toFixed(2) : 0} 
                  prefix="¥"
                  loading={loading}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="总订单数" 
                  value={statistics.totalOrders || 0}
                  loading={loading}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="成团率" 
                  value={statistics.successRate ? (statistics.successRate * 100).toFixed(2) : 0}
                  suffix="%"
                  loading={loading}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic 
                  title="活动数量" 
                  value={statistics.activityCount || 0}
                  loading={loading}
                />
              </Card>
            </Col>
          </Row>

          <Card title="销售额趋势" style={{ marginTop: 24 }}>
            <Line {...salesConfig} loading={loading} />
          </Card>

          <Card title="订单数量趋势" style={{ marginTop: 24 }}>
            <Line {...orderConfig} loading={loading} />
          </Card>

          <Row gutter={24} style={{ marginTop: 24 }}>
            <Col span={12}>
              <Card title="活动分布">
                <Pie {...activityPieConfig} loading={loading} />
              </Card>
            </Col>
            <Col span={12}>
              <Card title="热门活动">
                <Column {...popularConfig} loading={loading} />
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="活动分析" key="activity">
          <Card>
            <Table
              columns={activityColumns}
              dataSource={statistics.activityAnalysis || []}
              rowKey="id"
              loading={loading}
              pagination={false}
            />
          </Card>
        </TabPane>

        <TabPane tab="用户分析" key="user">
          <Card>
            <Row gutter={24}>
              <Col span={8}>
                <Card>
                  <Statistic 
                    title="参与用户数" 
                    value={statistics.userCount || 0}
                    loading={loading}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card>
                  <Statistic 
                    title="人均参与次数" 
                    value={statistics.avgParticipation ? statistics.avgParticipation.toFixed(2) : 0}
                    loading={loading}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card>
                  <Statistic 
                    title="人均消费金额" 
                    value={statistics.avgUserAmount ? (statistics.avgUserAmount / 100).toFixed(2) : 0}
                    prefix="¥"
                    loading={loading}
                  />
                </Card>
              </Col>
            </Row>

            <Card title="用户参与分布" style={{ marginTop: 24 }}>
              <Pie 
                data={statistics.userDistribution || []}
                angleField="value"
                colorField="type"
                radius={0.8}
                label={{
                  type: 'outer',
                  content: '{name} {percentage}',
                }}
                loading={loading}
              />
            </Card>
          </Card>
        </TabPane>
      </Tabs>
    </PageContainer>
  );
};

export default GroupbuyStatistics;